<?php
namespace app\beautiful\controller\admin\appointment;
use app\BaseController;
use app\beautiful\model\appointment\AppointmentModel;
use app\beautiful\model\appointment\CommissionModel;
use app\beautiful\model\appointment\PositionModel;
use app\beautiful\model\appointment\TechnicianModel;
use app\beautiful\model\appointment\TechnicianProjectModel;
use app\beautiful\model\project\ProjectModel;
use app\beautiful\model\project\ProjectTypeModel;
use app\common\logic\DataLogic;
use app\common\model\ShopStoreModel;

class Technician extends BaseController {
    protected $name='技师';

    public function index()
    {
        $name=$this->request->param('name');
        $mobile=$this->request->param('mobile');
        $status=$this->request->param('status/d',1);
        $store_id = $this->request->param('store_id/d',0);
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['status','=',$status],
            ['is_delete','=',0]
        ];
        if(!empty($name)) $where[]=['name','=',$name];
        if(!empty($mobile)) $where[]=['mobile','=',$mobile];

        $technician_model= new TechnicianModel();
        $technician_model = $technician_model->withCount(['projects'=>function($query){
            $query->where([['is_delete','=',0]]);
        }]);
        $order=['add_time'=>'desc'];$field="*";$append=['add_time_format','tags_string','status_means'];
        $limit=$this->request->limit;$page=$this->request->page;
        $return = DataLogic::getDataList($technician_model,$where,$order,$field,$limit,$page,$append);
        $total = $return['total'];
        if(!empty($return['list']) && $store_id > 0) {
            foreach($return['list'] as $key => $value) {
                if(empty($value['store'])) {
                    unset($return['list'][$key]);
                    $total = $total - 1;
                }
                $store = explode(',',$value['store']);
                if(!in_array($store_id,$store)) {
                    unset($return['list'][$key]);
                    $total = $total - 1;
                }
            }
            $return['list'] = array_values($return['list']);
            $return['total'] = $total;
        }
        $where_store = [
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['enable','=',1],
        ];
        $field='*';
        $order=['is_main'=>'asc','add_time'=>'desc'];
        $store = ShopStoreModel::where($where_store)->field($field)->order($order)->select()->toArray();
        $return['store'] = $store;
        return $this->success($return);
    }

    public function show()
    {
        $technician_id=$this->request->param('technician_id/d',0);
        if($technician_id==0) return $this->success([]);

        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');
        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($technician->is_delete != 0) return $this->error($this->name.'不存在');
        // 处理门店
        $store  = [];
        if(!empty($technician->store)) {
            $store = explode(',',$technician->store);
            foreach($store as &$v) {
                $v = intval($v);
            }
        }
        $form=[
            'face'=>$technician->face,
            'name'=>$technician->name,
            'mobile'=>$technician->mobile,
            'position'=>$technician->position,
            'position_id'=>$technician->position_id,
            'commission_id'=>$technician->commission_id,
            'working_collar'=>$technician->working_collar,
            'job_number'=>$technician->job_number,
            'brief_introduction'=>$technician->brief_introduction,
            'store' => $store
        ];

        return $this->success(['form'=>$form]);
    }

    public function save()
    {
        $technician_id=$this->request->param('technician_id/d',0);
        $face=$this->request->param('face');
        $name=$this->request->param('name');
        $mobile=$this->request->param('mobile');
        $working_collar=$this->request->param('working_collar/d',0);
        $job_number=$this->request->param('job_number');
        $position=$this->request->param('position');
        $brief_introduction=$this->request->param('brief_introduction');
        $store_id = $this->request->param('store_id/a',[]);

        $position_id=$this->request->param('position_id/d');
        $commission_id=$this->request->param('commission_id/d');
        //判断传来的参数
        if(empty($face)) return $this->error('请上传头像');
        if(empty($name)) return $this->error('请输入名称');
        if(empty($mobile) || !is_mobile($mobile)) return $this->error('请输入手机号');
        if(empty($working_collar) || $working_collar<=0) return $this->error('请输入工龄，且不能小于0');
        if(empty($job_number)) return $this->error('请输入工号');
        if(empty($brief_introduction) || mb_strlen($brief_introduction)>200) return $this->error('请输入简介，且字数不能多于200');
        if(empty($store_id)) return $this->error('请选择关联门店');
        if(empty($position_id)) return $this->error('请选择员工岗位');
        $positionmodel = PositionModel::find($position_id);
        if($positionmodel == null) return $this->error('所选岗位不存在');

        if(!empty($commission_id) && CommissionModel::find($commission_id)==null)return $this->error('所选提成方案不存在');

        if($technician_id != 0){
            if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');
            if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
            if($technician->status != 1) return $this->error($this->name.'不存在');
            if($technician->is_delete != 0) return $this->error($this->name.'不存在');
            $pre_face=$technician->face;
            //判断手机号的唯一性
            if($mobile != $technician->mobile){
                if(null !== TechnicianModel::where([
                        ['shop_id','=',$this->request->shopId],
                        ['status','=',1],
                        ['is_delete','=',0],
                        ['mobile','=',$mobile]
                    ])->find()){
                    return $this->error('该手机号已存在');
                }
            }
            //判断工号的唯一性
            if($job_number != $technician->job_number){
                if(null !== TechnicianModel::where([
                        ['shop_id','=',$this->request->shopId],
                        ['status','=',1],
                        ['is_delete','=',0],
                        ['job_number','=',$job_number]
                    ])->find()){
                    return $this->error('该工号已存在');
                }
            }
        }else{
            $technician = new TechnicianModel();
            $technician->shop_id = $this->request->shopId;
            $pre_face=null;
            //判断手机号的唯一性
            if(null !== TechnicianModel::where([
                    ['shop_id','=',$this->request->shopId],
                    ['status','=',1],
                    ['is_delete','=',0],
                    ['mobile','=',$mobile]
                ])->find()){
                return $this->error('该手机号已存在');
            }
            //判断工号的唯一性
            if(null !== TechnicianModel::where([
                    ['shop_id','=',$this->request->shopId],
                    ['status','=',1],
                    ['is_delete','=',0],
                    ['job_number','=',$job_number]
                ])->find()){
                return $this->error('该工号已存在');
            }
        }

        $technician->face=$face;
        $technician->name=$name;
        $technician->mobile=$mobile;
        $technician->position=$position;
        $technician->position_id=$position_id;
        $technician->commission_id=$commission_id;
        $technician->mobile=$mobile;
        $technician->working_collar=$working_collar;
        $technician->job_number=$job_number;
        $technician->brief_introduction=$brief_introduction;
        $technician->store = implode(',',$store_id);
        $technician->save();

//        imgReplaceAct($face,$pre_face);
        return $this->success(['id'=>$technician->technician_id]);
    }

    public function quit()
    {
        $technician_id=$this->request->param('technician_id/d',0);
        if($technician_id==0) return $this->error($this->name.'不存在');
        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');
        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($technician->is_delete != 0) return $this->error($this->name.'不存在');

        if($technician->status != 1) return $this->error($this->name.'已离职，请勿重复操作');

        //补充判断

        $technician->status = -1;
        $technician->save();
        return $this->success('离职成功');
    }

    public function del()
    {
        $technician_id=$this->request->param('technician_id/d',0);
        if($technician_id==0) return $this->error($this->name.'不存在');
        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');
        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($technician->is_delete != 0) return $this->error($this->name.'不存在');

        if($technician->status != -1) return $this->error($this->name.'离职状态才可删除');

        //补充判断

        $technician->is_delete = 1;
        $technician->save();
        return $this->success('删除成功');
    }

    /********************************************************* start 技师详情  start **************************************************************/

    public function detail()
    {
        $technician_id=$this->request->param('technician_id/d',0);
        if($technician_id==0) return $this->error($this->name.'不存在');
        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');
        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($technician->is_delete != 0) return $this->error($this->name.'不存在');

        $engaged_num=TechnicianProjectModel::where([
            ['shop_id','=',$this->request->shopId],
            ['technician_id','=',$technician_id]
        ])->sum('engaged_num') ?? 0;

        $projects_count=TechnicianProjectModel::where([
            ['shop_id','=',$this->request->shopId],
            ['technician_id','=',$technician_id],
            ['is_delete','=',0]
        ])->count() ?? 0;

        $detail=[
            'face'=>$technician->face,
            'name'=>$technician->name,
            'mobile'=>$technician->mobile,
            'working_collar'=>$technician->working_collar,
            'job_number'=>$technician->job_number,
            'brief_introduction'=>$technician->brief_introduction,
            'status'=>$technician->status,
            'status_means'=>$technician->status_means,
            'tags'=>$technician->tags ?? [],
            'engaged_num'=>$engaged_num,
            'projects_count'=>$projects_count,
        ];

        return $this->success(['detail'=>$detail]);
    }

    public function changTags()
    {
        $technician_id=$this->request->param('technician_id/d',0);
        $tags=$this->request->param('tags/a',[]);

        if($technician_id==0) return $this->error($this->name.'不存在');
        if(empty($tags) || !is_array($tags) || count($tags)==0) return $this->error('至少保留一个标签');

        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');
        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($technician->is_delete != 0) return $this->error($this->name.'不存在');

        $technician->tags=$tags;
        $technician->save();
        return $this->success('操作成功');
    }

    public function getTechnicianAppointmentList()
    {

        $technician_id=$this->request->param('technician_id/d',0);
        $status=$this->request->param('status/d',0);

        if($technician_id==0) return $this->error($this->name.'不存在');
        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');
        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($technician->is_delete != 0) return $this->error($this->name.'不存在');

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['technician_id','=',$technician_id],
        ];

        if(!empty($status)) $where[]=['status','=',$status];
        $appointment_model = new AppointmentModel();
        $appointment_model=$appointment_model->with(['member','technician']);
        $order=['add_time'=>'desc'];
        $field="*";
        $append=['add_time_format','status_means','operate_type_means','arrival_time_format','cancel_time_format'];
        $return = DataLogic::getDataList($appointment_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        return $this->success($return);
    }

    public function getTechnicianBindProjectList()
    {
        $technician_id=$this->request->param('technician_id/d',0);
        if($technician_id==0) return $this->error($this->name.'不存在');
        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');
        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($technician->is_delete != 0) return $this->error($this->name.'不存在');

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['technician_id','=',$technician_id],
            ['is_delete','=',0],
        ];

        $technician_project_model= new TechnicianProjectModel();
        $technician_project_model = $technician_project_model->with(['project']);
        $order=['add_time'=>'desc'];
        $field="*";
        $append=['add_time_format'];

        $return=DataLogic::getDataList($technician_project_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);
    }

    public function getProjectListFromTechnicianBind()
    {
        $technician_id=$this->request->param('technician_id/d',0);
        if($technician_id==0) return $this->error($this->name.'不存在');
        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');
        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($technician->is_delete != 0) return $this->error($this->name.'不存在');

        $project_ids=TechnicianProjectModel::where([
            ['shop_id','=',$this->request->shopId],
            ['technician_id','=',$technician_id],
            ['is_delete','=',0],
        ])->column('project_id') ?? [];

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['project_id','not in',$project_ids]
        ];

        $project_model= new ProjectModel();
        $order=['add_time'=>'desc'];
        $field='*';
        $append=['add_time_format'];
        $return = DataLogic::getDataList($project_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        return $this->success($return);
    }

    public function technicianBindProject()
    {
        $technician_id=$this->request->param('technician_id/d',0);
        $project_ids=$this->request->param('project_ids/a',[]);

        if($technician_id==0) return $this->error($this->name.'不存在');
        if(empty($project_ids) || !is_array($project_ids)) return $this->error('请选择项目');

        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');
        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($technician->is_delete != 0) return $this->error($this->name.'不存在');

        $bind_project_ids=TechnicianProjectModel::where([
                ['shop_id','=',$this->request->shopId],
                ['technician_id','=',$technician_id],
                ['is_delete','=',0],
            ])->column('project_id') ?? [];

        $project_ids = array_diff($project_ids,$bind_project_ids) ?? [];

        $project_ids = ProjectModel::where([
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['project_id','in',$project_ids]
        ])->column('project_id') ?? [];

        if(empty($project_ids)) return $this->error('请选择项目');
        $technician_project_data=[];
        foreach ($project_ids as $project_id){
            $technician_project_data[]=[
                'shop_id'=>$this->request->shopId,
                'project_id'=>$project_id,
                'technician_id'=>$technician_id
            ];
        }
        $technician_project_model= new TechnicianProjectModel();
        $technician_project_model->saveAll($technician_project_data);

        return $this->success('成功绑定');
    }

    public function delTechnicianProject()
    {
        $bind_id= $this->request->param('bind_id/d',0);
        if($bind_id==0) return $this->error('参数错误');
        if(null === $technician_project = TechnicianProjectModel::find($bind_id)) return $this->error('您未绑定这个项目');
        if($technician_project->shop_id != $this->request->shopId) return $this->error('您未绑定这个项目');
        if($technician_project->is_delete != 0) return $this->error('您未绑定这个项目');

        $technician_project->is_delete=1;
        $technician_project->save();
        return $this->success('删除成功');
    }


    /********************************************************* end 技师详情  end **************************************************************/


}
